package main

import (
	"github.com/gogap/logs"
	"yundian/internel/app/dao"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

func main() {
	//dingo.InitViper("./configs/adm.yaml")
	//dingo.InitViper("./configs/zmtest-adm.yaml")
	dingo.InitViper("./configs/zhongman.yaml")
	dbs.NewMysqlComponent().Step()

	var userIdArr []int
	var placesIdArr []int
	//userIds := []int{300649, 300782, 403276, 300869, 401433, 402536, 401433, 402536, 400775,
	//	400776, 400777, 400778, 400779, 400780, 400781, 400782, 400783, 401433, 402536}
	userIds := []int{300649, 300779, 300782, 300799, 300830, 300865, 300869, 300892, 300895, 400681, 400684, 400685, 400714, 400728,
		400775, 400776, 400777, 400778, 400779, 400780, 400781, 400782, 400783, 401203, 401433, 401823, 402536, 403276}
	for _, id := range userIds {
		uList := dao.NewUserDao().QueryChildUserIds(id).Unwrap().([]int)
		pList := dao.NewUserDao().GetPlacesIds(id, uList).Unwrap().([]int)

		userIdArr = append(userIdArr, uList...)
		placesIdArr = append(placesIdArr, pList...)
	}

	var placesList []struct {
		Id   int
		Date string
	}
	var tradeNoList []string

	pSql := `SELECT place_id id,DATE_FORMAT(min(end_date), '%Y-%m-%d')date FROM dividends_log 
	WHERE user_id IN (217,219,221) AND place_id IN (?) GROUP BY place_id`
	if db := global.Orm.Debug().Raw(pSql, placesIdArr).Find(&placesList); db.Error != nil {
		logs.Error(db.Error)
		return
	}

	oSql := `SELECT trade_no FROM orders o LEFT JOIN places p ON p.id=o.place_id WHERE p.branch_user_id=0 
	AND place_id=? AND DATE_FORMAT(FROM_UNIXTIME(o.create_at), '%Y-%m-%d')>=? AND o.trade_no>'ZM20210701' AND o.trade_no<'ZM20210831'`
	for _, item := range placesList {
		var list []string
		if db := global.Orm.Debug().Raw(oSql, item.Id, item.Date).Find(&list); db.Error != nil {
			logs.Error(db.Error)
			return
		}
		tradeNoList = append(tradeNoList, list...)
	}

	if db := global.Orm.Debug().Exec("DELETE FROM orders_user_relevancy WHERE trade_no IN (?)", tradeNoList); db.Error != nil {
		logs.Error(db.Error)
		return
	}
	if db := global.Orm.Debug().Exec("DELETE FROM dividends_log WHERE trade_no IN (?)", tradeNoList); db.Error != nil {
		logs.Error(db.Error)
		return
	}

	var orderListUse []orderListUseType
	orderSql := `SELECT o.*,p.branch_user_id,DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d')end_date,DATE_FORMAT(
	FROM_UNIXTIME(o.end_at), '%Y-%m')end_month FROM orders o LEFT JOIN places p ON o.parent_id=p.id WHERE o.trade_no in (?) 
	ORDER BY o.id`
	if db := global.Orm.Raw(orderSql, tradeNoList).Find(&orderListUse); db.Error != nil {
		logs.Error(db.Error)
		return
	}
	OrderRelevanceSyncDataExec(orderListUse, 300)
}
